package com.lcy.app.common.util;

import android.content.Context;
import android.os.Environment;

import com.lcy.app.contants.CommonContants;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;

public class FileUtil {
    /**
     * 获取应用可读写的的根目录
     */
    public static String getProjectExternalRootPath(boolean read) {
        if (read) {
            // 如果是读模式
            return Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download" +
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getPath() + "/main-project/";
        }
        // 如果是写模式
        return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getPath() + "/main-project/";
    }

    public static String getProjectInnerRootPath(Context context) {
        File file = new File(context.getFilesDir(), CommonContants.PROJECT_NAME);
        if (!file.exists()) {
            try {
                boolean newDir = file.mkdir();
            } catch (Exception e) {
                throw new RuntimeException("创建文件夹失败");
            }
        }
        return file.getAbsolutePath();
    }

    public static String readFile(String filePath) {
        return readFile(new File(filePath));
    }

    public static String readFile(File file) {
        FileReader fileReader = null;
        BufferedReader br = null;
        try {
            fileReader = new FileReader(file);
            br = new BufferedReader(fileReader);
            String line;
            String result = "";
            while ((line = br.readLine()) != null) {
                result += line;
            }
            return result;
        } catch (IOException e) {
            throw new RuntimeException("读文件失败");
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    public static void writeFile(String filePath, String content) {
        writeFile(new File(filePath), content);
    }

    public static void writeFile(File file, String content) {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(content.getBytes());
        } catch (IOException e) {
            throw new RuntimeException("写文件失败");
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
